<template>
    <div>
        <div>
            <el-config-provider :locale="zhCn"> <!--《:locale="zhCn 》设置语言-->

                <el-scrollbar height="70vh">
                    <!-- 请假申请 -->
                    <el-row :gutter="24">
                        <el-col :span="24">
                            <div class="grid-content ep-bg-purple-light" style="padding: 15px 0;">
                                <el-form-item label="请假申请" label-position="top"
                                    :style="{ fontSize: '15px', fontWeight: 'bold', borderBottom: '1px dashed #e4e7ed' }">
                                    <div class="progress-bar">
                                        <div class="progress"></div>
                                    </div>
                                </el-form-item>

                            </div>
                        </el-col>
                        <el-col :span="12">
                            <!-- {{ leaveData }} -->
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="请假单号"
                                    label-position="top">
                                    <el-input placeholder="自动生成无需填写" style="width: 354px;" disabled />
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <!-- {{ leaveDateData }} -->
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="申请日期"
                                    label-position="top">
                                    <el-input placeholder="" v-model="leaveData.applicationDate"
                                        style="/*width: 260px;*/" disabled />
                                </el-form-item>
                            </div>
                        </el-col>

                        <!--  -->
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="请假类型" label-position="top"
                                    required>
                                    <el-select v-model="leaveData.leaveType" style="width: 354px;" clearable filterable
                                        @change="handleLeaveTypeChange">

                                        <el-option v-for="item in options" :label="item.leaveType"
                                            :value="item.leaveType"></el-option>

                                    </el-select>

                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="姓名" label-position="top">
                                    <el-input placeholder="" :value="user.employeeName" style="/*width: 260px;*/"
                                        disabled />
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="所在部门"
                                    label-position="top">
                                    <el-input placeholder="" :value="user.department.deptName" style="/*width: 260px;*/"
                                        disabled />
                                </el-form-item>
                            </div>
                        </el-col>

                        <!--  -->
                        <el-col :span="24">
                            <!-- 空白分隔区域 -->
                            <div style="height: 10px; border-top: 0px dashed #e4e7ed; margin: 6px 0;"></div>
                        </el-col>

                        <!-- 假种说明 -->
                        <el-col :span="24">
                            <div class="grid-content ep-bg-purple-light">

                                <el-form-item label="假种说明" label-position="top">

                                    <el-table :data="holidaysTypeData" border stripe>
                                        <el-table-column v-for="col in holidaysType_columns" :prop="col.id"
                                            :key="col.id" :label="col.label" :width="col.width">
                                        </el-table-column>
                                    </el-table>

                                </el-form-item>

                            </div>
                        </el-col>
                        <!-- 请假日期 -->
                        <el-col :span="24">
                            <div class="grid-content ep-bg-purple-light">

                                <el-form-item label="请假日期" label-position="top">

                                    <el-table :data="leaveDateData" border stripe>
                                        <el-table-column type="index" width="50" />
                                        <el-table-column prop="leaveDate" label="请假日期" width="160">
                                            <template #default="scope">
                                                <el-date-picker v-model="scope.row.leaveDate" type="date"
                                                    placeholder="选择日期" style="width: 100%"
                                                    @change="calculateLeaveDays(scope.$index)" value-format="YYYY-MM-DD"
                                                    :disabled-date="disabledDate" />
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="leavePeriod" label="请假时段" width="160">
                                            <template #default="scope">
                                                <el-select v-model="scope.row.leavePeriod" style="width: 100%"
                                                    @change="calculateLeaveDays(scope.$index)">
                                                    <el-option label="上午" value="上午" />
                                                    <el-option label="下午" value="下午" />
                                                    <el-option label="全天" value="全天" />
                                                </el-select>
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="leaveDays" label="请假天数小计" width="160">
                                            <template #default="scope">
                                                <el-input v-model="scope.row.leaveDays" disabled style="width: 100%" />
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="attendanceCycle" label="归属考勤周期" width="200">
                                            <template #default="scope">
                                                <el-input v-model="scope.row.attendanceCycle" disabled
                                                    style="width: 100%" />
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="操作" width="80">
                                            <template #default="scope">
                                                <el-button size="small" type="danger"
                                                    @click="removeRow(scope.$index)">删除</el-button>
                                            </template>
                                        </el-table-column>
                                    </el-table>

                                </el-form-item>

                                <div class="action-btns" style="margin-top: 12px">
                                    <el-button type="primary" icon="Plus" @click="addRow">
                                        添加
                                    </el-button>
                                </div>
                            </div>
                        </el-col>

                        <!--  -->
                        <el-col :span="24">
                            <!-- 空白分隔区域 -->
                            <div style="height: 10px; border-top: 0px dashed #e4e7ed; margin: 6px 0;"></div>
                        </el-col>

                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="合计请假天数"
                                    label-position="top" required>
                                    <el-input placeholder="" v-model="totalLeaveDays" style="width: 354px;" disabled />
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="请假事由说明"
                                    label-position="top" required>
                                    <el-input v-model="textarea" style="width: 633px;" :rows="6" type="textarea"
                                        placeholder="" />
                                </el-form-item>
                            </div>
                        </el-col>

                        <div class="bottom-submit-bar">
                            <el-button type="primary" @click="submitLeaveApplication">提交</el-button>
                            <!-- <el-button>保存草稿</el-button> -->
                        </div>

                    </el-row>
                </el-scrollbar>

            </el-config-provider>
        </div>
    </div>
</template>

<script setup>
import { ref, watch, onMounted, defineEmits } from 'vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ElMessage, ElMessageBox } from 'element-plus'
import router from '@/router';
import request from '@/api/request';

let emits = defineEmits(['ref-table']);

const leaveData = ref({})
const textarea = ref('')
const totalLeaveDays = ref('')

// 获取session中的用户信息 - 需要解析JSON字符串
let user = JSON.parse(sessionStorage.getItem('user') || '{}');

// 请假日期数据源
const leaveDateData = ref([{
    leaveDate: '',
    leavePeriod: '',
    leaveDays: '',
    attendanceCycle: ''
}])

// 请假类型选项
const options = ref([{}])

// 假种说明
const holidaysType_columns = ref([
    { id: 'leaveType', label: '请假类型', width: '160' },
    { id: 'leaveLength', label: '请假步长', width: '160' },
    { id: 'rangeApplication', label: '适用范围', width: '160' },
    { id: 'reason', label: '请假说明', width: '200' },
])
// 假种说明数据源
const holidaysTypeData = ref([])

// 请假日期列配置
const leaveDate_columns = ref([
    { id: 'leaveDate', label: '请假日期', width: '160' },
    { id: 'leavePeriod', label: '请假时段', width: '160' },
    { id: 'leaveDays', label: '请假天数小计', width: '160' },
    { id: 'attendanceCycle', label: '归属考勤周期', width: '200' },
])

// 加载假种类型
const loadholidaysTypes = () => {
    request({
        url: "/holidayType/list",
        method: "get"
    }).then(resp => {
        options.value = resp.data
    })
}

const disabledDate = (time) => {
    // 禁用今天之前的日期（不包括今天）
    return time.getTime() < new Date(new Date().setHours(0, 0, 0, 0));
};

// 监听请假类型变化
watch(() => leaveData.value.leaveType, (newleaveType) => {
    if (newleaveType) {
        request({
            url: "/holidayType/findByLeaveType",
            method: "get",
            params: { leaveType: newleaveType }
        }).then(resp => {
            holidaysTypeData.value = resp.data
        })
    } else {
        holidaysTypeData.value = []
    }
})

loadholidaysTypes()

// 处理请假类型变化
const handleLeaveTypeChange = () => {
    // 清空之前的请假日期数据
    leaveDateData.value = [{
        leaveDate: '',
        leavePeriod: '',
        leaveDays: '',
        attendanceCycle: ''
    }]
}

// 添加新的请假日期行
const addRow = () => {
    leaveDateData.value.push({
        leaveDate: '',
        leavePeriod: '',
        leaveDays: '',
        attendanceCycle: ''
    })
}

// 删除指定的请假日期行
const removeRow = (index) => {
    if (leaveDateData.value.length <= 1) {
        ElMessage.warning('至少需要保留一条请假记录')
        return
    }
    leaveDateData.value.splice(index, 1)
    calculateTotalLeaveDays()
}

// 计算单条请假记录的天数
const calculateLeaveDays = (index) => {
    const row = leaveDateData.value[index]

    if (!row.leaveDate || !row.leavePeriod) {
        row.leaveDays = ''
        row.attendanceCycle = ''
        return
    }

    // 根据请假时段计算天数
    let days = 0
    if (row.leavePeriod === '上午') {
        days = 0.5
    } else if (row.leavePeriod === '下午') {
        days = 0.5
    } else if (row.leavePeriod === '全天') {
        days = 1
    }

    row.leaveDays = days

    // 计算归属考勤周期
    const date = new Date(row.leaveDate)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const formattedMonth = month < 10 ? `0${month}` : `${month}`
    row.attendanceCycle = `${year}-${formattedMonth}`
}

// 计算总请假天数
const calculateTotalLeaveDays = () => {
    let total = 0
    leaveDateData.value.forEach(row => {
        if (row.leaveDays) {
            total += parseFloat(row.leaveDays)
        }
    })
    totalLeaveDays.value = total.toFixed(1)
}

// 提交请假申请
const submitLeaveApplication = () => {
    // 验证必填项
    if (!leaveData.value.leaveType) {
        ElMessage.warning('请选择请假类型')
        return
    }

    if (leaveDateData.value.length === 0) {
        ElMessage.warning('请至少添加一条请假记录')
        return
    }

    // 验证每条请假记录
    for (let i = 0; i < leaveDateData.value.length; i++) {
        const row = leaveDateData.value[i]
        if (!row.leaveDate) {
            ElMessage.warning(`第${i + 1}条请假记录缺少请假日期`)
            return
        }
        if (!row.leavePeriod) {
            ElMessage.warning(`第${i + 1}条请假记录缺少请假时段`)
            return
        }
    }

    // 检查重复日期和时段
    const datePeriodMap = new Map()
    for (let i = 0; i < leaveDateData.value.length; i++) {
        const row = leaveDateData.value[i]
        const dateStr = row.leaveDate instanceof Date 
            ? row.leaveDate.toISOString().split('T')[0] 
            : row.leaveDate
        
        const key = `${dateStr}_${row.leavePeriod}`
        if (datePeriodMap.has(key)) {
            ElMessage.warning(`存在重复的日期和时段：${dateStr} ${row.leavePeriod}`)
            return
        }
        datePeriodMap.set(key, true)
    }

    // 提交数据
    const submitData = {
        leaveApplication: leaveDateData.value.map(row => ({
            ...leaveData.value,
            leaveDate: row.leaveDate,
            leavePeriod: row.leavePeriod,
            duration: row.leaveDays,
            attendanceCycle: row.attendanceCycle,
            reason: textarea.value,
        })),
        // totalLeaveDays: totalLeaveDays.value
    }

    console.log("提交数据", submitData.leaveApplication)

    // 调用API提交
    request({
        url: "/leaveApplication/insertBatch",
        method: "post",
        data: submitData.leaveApplication
    }).then(resp => {
        ElMessage.success(resp.msg)
        emits('ref-table')
    }).catch(error => {
        ElMessage.error('提交失败')
    })
}

// 监听请假日期数据变化，自动计算总天数
watch(leaveDateData, () => {
    calculateTotalLeaveDays()
}, { deep: true })

// 初始化时计算总天数
calculateTotalLeaveDays()

// 设置当前日期时间
const setCurrentDateTime = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    // const hours = String(now.getHours()).padStart(2, '0');
    // const minutes = String(now.getMinutes()).padStart(2, '0');
    // const seconds = String(now.getSeconds()).padStart(2, '0');
    //  ${hours}:${minutes}:${seconds}
    leaveData.value.applicationDate = `${year}-${month}-${day}`;
}

// 组件挂载时设置当前日期时间
onMounted(() => {
    setCurrentDateTime();
})

</script>

<style scoped>
/* 外层容器，可控制整体条的高度、圆角等 */
.progress-bar {
    height: 6px;
    background-color: #ccebf7;
    border-radius: 3px;
    display: flex;
    width: 100%;
    /* 确保进度条容器宽度占满父容器 */
    overflow: hidden;
    /* 防止子元素溢出 */
}

.progress {
    width: 8%;
    height: 10;
    background-color: #61c3ea;
    border-radius: 3px 0 0 3px;
    transition: width 0.3s ease;
    /* 添加宽度变化的过渡效果 */
}

.bottom-submit-bar {
    /* position: fixed; */
    /* 固定定位 */
    bottom: 0;
    /* 靠底部 */
    left: 0;
    width: 100%;
    background-color: #fff;
    /* 背景色，可根据需求调整 */
    border-top: 1px solid #eaeaea;
    /* 顶部边框，与页面区分 */
    padding: 12px 24px;
    /* 内边距，适配截图里的间距风格 */
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    /* 按钮靠左，可根据实际需求调整 */
    z-index: 10;
    /* 提高层级，避免被其他内容覆盖 */
}
</style>